package adminService

import (
	"errors"
	"gitee.com/yangguoliang001/go-gin-vue3/QO"
	"gitee.com/yangguoliang001/go-gin-vue3/model"
	"gitee.com/yangguoliang001/go-gin-vue3/pkg/response"
	"gitee.com/yangguoliang001/go-gin-vue3/util"
	"gitee.com/yangguoliang001/go-gin-vue3/util/code"
	"gitee.com/yangguoliang001/go-gin-vue3/vo"
	"github.com/gin-gonic/gin"
)

func (a *AdminService) QueryAdminByUsername(c *gin.Context, username string) (admin model.AdminDO, err error) {
	admin, err = a.adminDao.QueryAdminByUsername(username)
	// 查询用户失败，用户不存在
	if err != nil {
		response.Fail(c, code.AdminDetailError, code.Text(code.AdminDetailError), gin.H{"realErr": err})
		return
	}
	return
}

func (a *AdminService) QueryAdminList(c *gin.Context, adminListReq QO.AdminListReq) (adminListRes vo.AdminListVO, err error) {
	adminListRes, err = a.adminDao.QueryAdminList(adminListReq)
	if err != nil {
		response.Fail(c, code.AdminListError, code.Text(code.AdminListError), gin.H{"realErr": err})
		return vo.AdminListVO{}, err
	}
	return adminListRes, nil
}

func (a *AdminService) AddAdmin(c *gin.Context, adminReq QO.AdminReq) (err error) {
	var affectedRow int64
	adminReq.Password, _ = util.GeneratePassword(adminReq.Password)
	affectedRow, err = a.adminDao.AddAdmin(adminReq)
	if err != nil {
		response.Fail(c, code.AdminCreateError, code.Text(code.AdminCreateError), gin.H{"realErr": err})
		return err
	}
	if affectedRow == 0 {
		response.Fail(c, code.AdminCreateError, code.Text(code.AdminCreateError), gin.H{"realErr": "管理员已存在"})
		return errors.New("管理员已存在")
	}
	return nil
}

func (a *AdminService) DisabledAdmin(c *gin.Context, adminReq QO.AdminIdReq) (err error) {
	err = a.adminDao.DisabledAdmin(adminReq)
	if err != nil {
		response.Fail(c, code.AdminUpdateError, code.Text(code.AdminUpdateError), gin.H{"realErr": err})
		return err
	}
	return nil
}

func (a *AdminService) DeletedAdmin(c *gin.Context, id int32) (err error) {
	err = a.adminDao.DeletedAdmin(id)
	if err != nil {
		response.Fail(c, code.AdminDeleteError, code.Text(code.AdminDeleteError), gin.H{"realErr": err})
		return err
	}
	return nil
}
